<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

class Privatesea extends Backend
{
    protected $model = null;
    //关联查询的意思
    protected $relationSearch = true;
    //数据限制
    // 只看自己
    protected $dataLimit = 'personal';

    //数据记录控制的外键字段 前提是数据库表中一定要有这个字段才行
    protected $dataLimitField = 'adminid';
    public function __construct()
    {
        parent::__construct();
        $this->model = model("Business.Business");
        $this->SourceModel = model("Business.Source");
        $this->ReceiveModel = model("Business.Receive");
        $this->RegionModel = model('Region');
        $SourceList = $this->SourceModel->select();
        $Sourcdata = [];
        foreach ($SourceList as $val) {
            $Sourcdata[$val['id']] = $val['name'];
        }
        $Sexlist = ['0' => '保密', '1' => '男', '2' => '女',];
        $DealList = ['0' => '未成交', '1' => '已成交'];
        $this->assign([
            'Sexlist' => $Sexlist,
            'DealList' => $DealList,
            'Sourcdata' => $Sourcdata,
        ]);

    }
    public function index()
    {
        if ($this->request->isAjax()) {
            //接收参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with(['source', 'admin'])
                ->where($where)
                ->where('adminid', $this->auth->id)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['source', 'admin'])
                ->where($where)
                ->where('adminid', $this->auth->id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            //返回json数据
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }
        return $this->view->fetch();
    }
    public function add()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->param('row/a');
            // 手机号码就是密码
            $password = $params['mobile'];
            $salt = build_ranstr();
            $params['password'] = md5($password . $salt);
            $data = [
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'password' => $params['password'],
                'salt' => $salt,
                'gender' => $params['gender'],
                'sourceid' => $params['sourceid'],
                'deal' => $params['deal'],
                'adminid' => $this->auth->id,
                'money' => 0,
                'email' => $params['email']
            ];
            // 修改省市区
            if ($params['region']) {
                $region = explode('/', $params['region']);

                if (count($region) < 3) {
                    $this->error('请重新选择省市区!');
                }
                $pathcode = $this->RegionModel->where('name', $region[2])->value('parentpath');

                $pathcode = explode(',', $pathcode);

                list($province, $city, $district) = $pathcode;
                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;

            }
            // halt($data);
            // exit;
            if ($data) {
                // 开启事务
                $this->model->startTrans();
                $this->ReceiveModel->startTrans();
                $BuStatus = $this->model->validate('common/business/Business')->save($data);
                if ($BuStatus === FALSE) {
                    $this->model->rollback();
                    $this->error($this->model->getError());
                }
                $list = [
                    'applyid' => $this->auth->id,
                    'status' => 'apply',
                    'busid' => $this->model->id
                ];
                $reStatus = $this->ReceiveModel->save($list);
                if ($reStatus === FALSE) {
                    $this->ReceiveModel->rollback();
                    $this->error($this->ReceiveModel->getError());
                }
                if ($BuStatus === FALSE || $reStatus === FALSE) {
                    // 事务回滚
                    $this->model->rollback();
                    $this->ReceiveModel->rollback();
                    $this->error('添加失败');
                    exit;
                } else {
                    $this->model->commit();
                    $this->ReceiveModel->commit();
                    $this->success('添加成功');
                    exit;
                }
            }
        }
        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No results were found'));
            exit;
        }
        // 省份
        $province = $this->RegionModel->where('code', $row['province'])->value('name');
        // 市
        $city = $this->RegionModel->where('code', $row['city'])->value('name');
        // 区
        $district = $this->RegionModel->where('code', $row['district'])->value('name');

        $region = [
            'province' => $row['province'],
            'city' => $row['city'],
            'district' => $row['district']
        ];
        $region = $province . '/' . $city . '/' . $district;
        $this->assign([
            'row' => $row,
            'region' => $region
        ]);
        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');
            $data = [
                'id' => $ids,
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'gender' => $params['gender'],
                'sourceid' => $params['sourceid'],
                'deal' => $params['deal'],
                'email' => $params['email'],
                'avatar'=>$params['avatar']
            ];
            // halt($data);
            // exit;
            // 修改省市区
            if ($params['region']) {
                $region = explode('/', $params['region']);

                if (count($region) < 3) {
                    $this->error('请重新选择省市区!');
                }
                $pathcode = $this->RegionModel->where('name', $region[2])->value('parentpath');

                $pathcode = explode(',', $pathcode);

                list($province, $city, $district) = $pathcode;
                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;
            }
            // $validate = [
            //     'mobile' => ['require', 'number'],
            //     'email' => 'email'
            // ];
            $result = $this->model->isUpdate(true)->save($data);
            if ($result === FALSE) {
                if ($params['avatar'] && $params['avatar'] != $row['avatar']) {
                    $avatar = substr($params['avatar'], 1);
                    @is_file($avatar) && @unlink($avatar);
                }
                $this->error($this->model->getError());
                exit;
            } else {
                $this->success();
                exit;
            }

        }
        return $this->view->fetch();
    }
    public function recycle($ids = null)
    {
        $ids = empty($ids) ? [] : explode(',', $ids);
        // halt($ids);
        // exit;
        $data = [];
        $list = [];
        foreach ($ids as $item) {
            $row = $this->model->find($ids);
            if (!$row) {
                $this->error(__('No results were found'));
                exit;
            }
            $list[] = [
                'applyid' => $this->auth->id,
                'status' => 'recovery',
                'busid' => $item
            ];
            $data[] = [
                'id' => $item,
                'adminid' => null
            ];
            // array_push($data,$data);
            // var_dump($data);
        }
        // halt($data);
        // exit;
        // 开启事务
        $this->model->startTrans();
        $this->ReceiveModel->startTrans();

        $BuStatus = $this->model->isUpdate(true)->saveAll($data);
        if ($BuStatus === FALSE) {
            $this->model->rollback();
            $this->error($this->model->getError());
        }
        $reStatus = $this->ReceiveModel->saveAll($list);
        if ($reStatus === FALSE) {
            $this->ReceiveModel->rollback();
            $this->error($this->ReceiveModel->getError());
        }
        if ($BuStatus === FALSE || $reStatus === FALSE) {
            // 事务回滚
            $this->model->rollback();
            $this->ReceiveModel->rollback();
            $this->error('回收失败');
            exit;
        } else {
            $this->model->commit();
            $this->ReceiveModel->commit();
            $this->success('回收成功');
            exit;
        }
    }
    public function info($ids = NULL)
    {
        $row = $this->model->find($ids);

        if (!$row) {
            $this->error(__('No results were found'));
            exit;
        }

        // var_dump($row->toArray());
        // exit;

        $this->assign('row', $row);

        return $this->view->fetch();
    }
}